# -*- coding: utf-8 -*-
import scrapy
from scrapy.pipelines.images import ImagesPipeline
from scrapy.utils.project import get_project_settings
import os,json

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html


class DongQDPipeline(ImagesPipeline):

    IMAGES_STORE = get_project_settings().get('IMAGES_STORE')

    # def __init__(self):
    #     super(DongQDPipeline, self).__init__()
    #     self.save_json = open('./json', 'wb')

    def get_media_requests(self, item, info):
        image_url = item['thumb']
        yield scrapy.Request(image_url)


    def item_completed(self, results, item, info):
        image_path = [x['path'] for ok, x in results if ok]
        print(image_path[0])
        item['file_local'] = os.path.join(self.IMAGES_STORE,image_path[0])
        # sava_da = json.dumps(dict(item), ensure_ascii=False)
        # self.save_json.write(sava_da.encode('utf-8') + '\n')
        return item

    # def close_spider(self, spider):
    #     print('close')
    #     self.save_json.close()


